import 'package:city_pickers/city_pickers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json2dart_safe/json2dart.dart';
import 'package:pornhub_app/components/ad_banner/ad_banner.dart';
import 'package:pornhub_app/components/text_view.dart';
import 'package:pornhub_app/model/community/city_list_model.dart';
import 'package:pornhub_app/model/community/city_model.dart';
import 'package:pornhub_app/model/community/province_list_model.dart';
import 'package:pornhub_app/model/community/province_model.dart';
import 'package:pornhub_app/services/user_service.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/enum.dart';
import 'package:pornhub_app/views/engagement/views/engagement_city_page.dart';
import 'package:pornhub_app/views/engagement/views/engagement_vertical_list_page.dart';
import 'package:pornhub_app/views/engagement/views/engagement_station_list_page.dart';

class EngagementClassifyPage extends StatefulWidget {
  final String classifyId;

  const EngagementClassifyPage({super.key, required this.classifyId});

  @override
  State createState() => _EngagementClassifyPageState();
}

class _EngagementClassifyPageState extends State<EngagementClassifyPage>
    with SingleTickerProviderStateMixin {
  late TabController tabController;
  final us = Get.find<UserService>();

  CityListModel get city => us.city;

  ProvinceListModel get province => us.province;
  List<CityModel> hotList = [];
  var currentCity = '全国'.obs;

  Future _initCity() async {
    hotList.add(CityModel.recommend());
    if (city.listHot != null) {
      hotList.addAll(city.listHot ?? []);
    }
  }

  late List<ProvinceModel> _provinceList = [];
  late List<CityModel> cityList = [];
  Map<String, String> provincesData = {};
  Map<String, dynamic> citiesData = {};

  Future _initCityData() async {
    if (province.data != null) {
      _provinceList = province.data ?? [];
      if (_provinceList.isNotEmpty) {
        for (int i = 0; i < _provinceList.length; i++) {
          provincesData.put('${_provinceList[i].code}', _provinceList[i].name);
          if (_provinceList[i].cityList != null) {
            cityList = _provinceList[i].cityList ?? [];
            if (cityList.isNotEmpty) {
              Map<String, dynamic> citiesChildData = {};
              for (int j = 0; j < cityList.length; j++) {
                Map<String, String> citiesChildData02 = {};
                citiesChildData02.put('name', cityList[j].name);
                if (cityList[j].code == _provinceList[i].code) {
                  int code = int.tryParse('${cityList[j].code}') ?? 0;
                  citiesChildData.put('${(code + 100)}', citiesChildData02);
                } else {
                  citiesChildData.put('${cityList[j].code}', citiesChildData02);
                }
                citiesData.put('${_provinceList[i].code}', citiesChildData);
              }
            }
          }
        }
      }
    }
  }

  @override
  void initState() {
    _initCityData();
    _initCity();
    tabController = TabController(length: hotList.length, vsync: this);
    super.initState();
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  Widget buildTabBar() {
    return Padding(
      padding: EdgeInsets.only(top: 22.h, right: 90.w, bottom: 14.h),
      child: SizedBox(
        height: 20.h,
        child: TabBar(
            isScrollable: true,
            tabAlignment: TabAlignment.start,
            labelColor: COLOR.hexColor('#DD001B'),
            unselectedLabelColor: COLOR.hexColor('#666666'),
            labelStyle: TextStyle(fontSize: 14.w, fontWeight: FontWeight.w400),
            unselectedLabelStyle:
                TextStyle(fontSize: 14.w, fontWeight: FontWeight.w400),
            dividerColor: Colors.transparent,
            controller: tabController,
            indicator: const BoxDecoration(),
            indicatorColor: Colors.transparent,
            tabs: hotList.map((v) => Tab(text: '${v.name}')).toList()),
      ),
    );
  }

  // /// 中国省份信息
  // Map<String, String> provincesData = {
  //   "110000": "北京市",
  //   "120000": "天津市",
  //   "130000": "河北省",
  //   "140000": "山西省",
  //   "150000": "内蒙古自治区",
  // };
  //
  // /// 中国城市信息
  // Map<String, dynamic> citiesData = {
  //   "110000": {
  //     "110100": {"name": "北京城区", "alpha": "b"}
  //   },
  //   "120000": {
  //     "120100": {"name": "天津城区", "alpha": "t"}
  //   },
  //   "130000": {
  //     "130100": {"name": "石家庄市", "alpha": "s"},
  //     "130200": {"name": "唐山市", "alpha": "t"},
  //     "130300": {"name": "秦皇岛市", "alpha": "q"},
  //     "130400": {"name": "邯郸市", "alpha": "h"},
  //     "130500": {"name": "邢台市", "alpha": "x"},
  //     "130600": {"name": "保定市", "alpha": "b"},
  //     "130700": {"name": "张家口市", "alpha": "z"},
  //     "130800": {"name": "承德市", "alpha": "c"},
  //     "130900": {"name": "沧州市", "alpha": "c"},
  //     "131000": {"name": "廊坊市", "alpha": "l"},
  //     "131100": {"name": "衡水市", "alpha": "h"}
  //   },
  //   "140000": {
  //     "140100": {"name": "太原市", "alpha": "t"},
  //     "140200": {"name": "大同市", "alpha": "d"},
  //     "140300": {"name": "阳泉市", "alpha": "y"},
  //     "140400": {"name": "长治市", "alpha": "c"},
  //     "140500": {"name": "晋城市", "alpha": "j"},
  //     "140600": {"name": "朔州市", "alpha": "s"},
  //     "140700": {"name": "晋中市", "alpha": "j"},
  //     "140800": {"name": "运城市", "alpha": "y"},
  //     "140900": {"name": "忻州市", "alpha": "x"},
  //     "141000": {"name": "临汾市", "alpha": "l"},
  //     "141100": {"name": "吕梁市", "alpha": "l"}
  //   },
  //   "150000": {
  //     "150100": {"name": "呼和浩特市", "alpha": "h"},
  //     "150200": {"name": "包头市", "alpha": "b"},
  //     "150300": {"name": "乌海市", "alpha": "w"},
  //     "150400": {"name": "赤峰市", "alpha": "c"},
  //     "150500": {"name": "通辽市", "alpha": "t"},
  //     "150600": {"name": "鄂尔多斯市", "alpha": "e"},
  //     "150700": {"name": "呼伦贝尔市", "alpha": "h"},
  //     "150800": {"name": "巴彦淖尔市", "alpha": "b"},
  //     "150900": {"name": "乌兰察布市", "alpha": "w"},
  //     "152200": {"name": "兴安盟", "alpha": "x"},
  //     "152500": {"name": "锡林郭勒盟", "alpha": "x"},
  //     "152900": {"name": "阿拉善盟", "alpha": "a"}
  //   },
  // };

  showCityPicker() async {
    Result? result = await CityPickers.showCityPicker(
      context: context,
      showType: ShowType.pc,
      cancelWidget: TextView(
        text: "取消",
        fontSize: 18.sp,
        color: COLOR.color_333333,
        fontWeight: FontWeight.w500,
      ),
      confirmWidget: TextView(
        text: "确定",
        fontSize: 18.sp,
        color: COLOR.color_333333,
        fontWeight: FontWeight.w500,
      ),
      citiesData: citiesData,
      provincesData: provincesData,
      height: 250.w,
      borderRadius: 10,
    );
    if (result != null) {
      currentCity.value = result.cityName ?? result.provinceName ?? "全国";
      Navigator.push(
          Get.context!,
          MaterialPageRoute(
              builder: (context) => EngagementCityPage(
                    classifyId: widget.classifyId,
                    cityName: currentCity.value,
                    meetType: 1,
                  )));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverToBoxAdapter(
              child: const AdBanner(adress: AdPlaceNameEnum.NDD_BANNER)
                  .marginOnly(left: 14.w, top: 5.w, right: 14.w),
            ),
            SliverToBoxAdapter(
              child: Stack(
                children: <Widget>[
                  buildTabBar(),
                  Positioned(
                    right: 3.w,
                    bottom: 18.w,
                    child: InkWell(
                      onTap: () {
                        showCityPicker();
                        // _example2();
                      },
                      child: Container(
                        color: Colors.white,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Image.asset(
                              'assets/engagement/icon_city.png',
                              width: 15.w,
                              height: 15.w,
                            ),
                            SizedBox(width: 5.w),
                            Obx(
                              () => Text(
                                currentCity.value,
                                style: TextStyle(
                                    color: COLOR.hexColor('#DD001B'),
                                    fontSize: 14.w,
                                    fontWeight: FontWeight.w400),
                              ),
                            ),
                            Icon(
                              Icons.chevron_right,
                              color: COLOR.hexColor('#DD001B'),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ];
        },
        body: TabBarView(
          controller: tabController,
          children: hotList.map((e) {
            switch (e.name) {
              case "最受欢迎":
                return const EngagementStationListPage();
              default:
                return EngagementVerticalListPage(
                  dataType: 1,
                  meetType: 1,
                  classifyId: widget.classifyId,
                  cityName: e.name ?? '',
                );
            }
          }).toList(),
        ),
      ),
    );
  }
}
